<template>
	<view class="">
		<titleBar title="商品详情" :isSubPage="true"></titleBar>
		<image :src="productImages" mode="aspectFill" style="width: 100%; height: 900rpx;"></image>
		<view class="container">

			<!-- 商品基本信息 -->
			<view class="product-basic-info">
				<view class="product-price-row">
					<text class="product-price">¥{{ productInfo.price.toFixed(2) }}</text>
					<text class="product-original-price" v-if="productInfo.originalPrice">
						¥{{ productInfo.originalPrice.toFixed(2) }}
					</text>
				</view>
				<view class="product-tags">
					<view class="product-tag" v-for="(tag, index) in productInfo.tags" :key="index">
						{{ tag }}
					</view>
				</view>
				<text class="product-name">{{ productInfo.name }}</text>
				<view class="product-stats">
					<text class="product-stat">销量: {{ productInfo.salesCount }}</text>
					<text class="product-stat">评价: {{ productInfo.reviewCount }}</text>
				</view>
			</view>

			<!-- 商品规格选择 -->
			<view class="product-specs">
				<view class="specs-header">
					<text class="specs-title">规格选择</text>
					<text class="specs-selected">已选: {{ getSelectedSpecsText() }}</text>
				</view>

				<view class="specs-section" v-for="(spec, specIndex) in productSpecs" :key="specIndex">
					<text class="spec-type">{{ spec.name }}</text>
					<view class="spec-options">
						<view class="spec-option" v-for="(option, optionIndex) in spec.options" :key="optionIndex"
							:class="{ 'active': selectedSpecs[spec.name] === option.value, 'disabled': !option.available }"
							@click="selectSpec(spec.name, option.value, option.available)">
							{{ option.label }}
						</view>
					</view>
				</view>

				<view class="quantity-section">
					<text class="quantity-label">数量</text>
					<view class="quantity-control">
						<view class="quantity-btn" @click="decreaseQuantity">-</view>
						<input type="number" class="quantity-input" v-model="quantity" />
						<view class="quantity-btn" @click="increaseQuantity">+</view>
					</view>
				</view>
			</view>

			<!-- 店铺信息 -->
			<view class="shop-info">
				<image :src="productInfo.brandLogo" mode="aspectFill" class="shop-logo"></image>
				<view class="shop-detail">
					<text class="shop-name">{{ productInfo.brandName }}</text>
					<view class="shop-stats">
						<text class="shop-stat">商品: {{ productInfo.brandProductCount }}</text>
						<text class="shop-stat">关注: {{ productInfo.brandFollowerCount }}</text>
					</view>
				</view>
				<button class="btn-check-shop" @click="navigateToBrand(productInfo.brandId)">进店逛逛</button>
			</view>

			<!-- 商品详情区域 -->
			<view class="product-details">
				<view class="tabs">
					<view class="tab" v-for="(tab, index) in tabs" :key="index"
						:class="{ 'active': currentTab === index }" @click="switchTab(index)">
						{{ tab }}
					</view>
				</view>

				<view class="tab-content">
					<!-- 商品介绍 -->
					<view v-if="currentTab === 0" class="product-description">
						<rich-text :nodes="productInfo.description"></rich-text>
					</view>

					<!-- 规格参数 -->
					<view v-if="currentTab === 1" class="product-params">
						<view class="param-item" v-for="(param, index) in productInfo.params" :key="index">
							<text class="param-name">{{ param.name }}</text>
							<text class="param-value">{{ param.value }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 猜你喜欢 -->
			<view class="recommended">
				<view class="section-title">猜你喜欢</view>
				<scroll-view scroll-x class="recommended-list">
					<view class="recommended-item" v-for="(item, index) in recommendedProducts" :key="index"
						@click="navigateToDetail(item.id)">
						<image :src="item.picture" mode="aspectFill" class="recommended-image"></image>
						<text class="recommended-name">{{ item.tradeName }}</text>
						<text class="recommended-price">¥{{ item.prices.toFixed(2) }}</text>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 底部购买栏 -->
		<view class="bottom-bar">
			<view class="action-buttons">
				<!-- <view class="action-btn" @click="contactShop">
					<text class="action-icon">💬</text>
					<text class="action-text">客服</text>
				</view> -->
				<view class="action-btn cart-btn" @click="navigateToCart">
					<text class="action-icon">🛒</text>
					<text class="action-text">购物车</text>
					<text class="cart-badge" v-if="cartItemCount > 0">{{ cartItemCount }}</text>
				</view>
			</view>
			<view class="purchase-buttons">
				<button class="btn-add-cart" @click="addToCart">+购物车</button>
				<button class="btn-buy-now" @click="buyNow">立即购买</button>
			</view>
		</view>

		<!-- 购物车成功提示 -->
		<view class="add-cart-popup" v-if="showCartPopup">
			<view class="popup-content">
				<text class="popup-icon">✓</text>
				<text class="popup-text">已加入购物车</text>
			</view>
		</view>
	</view>
</template>

<script>
	import titleBar from '@/components/titleBar.vue'
	import {
		productApi
	} from '@/api/user.js'
	export default {
		components: {
			titleBar
		},
		data() {
			return {
				productId: null,
				productInfo: {
					id: 1,
					name: "宠物狗粮专业配方 泰迪贵宾专用狗粮小型犬成犬通用型天然粮2.5kg",
					price: 129.90,
					originalPrice: 159.90,
					salesCount: 2354,
					reviewCount: 986,
					rating: 4.8,
					tags: ["限时特惠", "品牌自营", "满减"],
					brandId: 1,
					brandName: "品牌名称",
					brandLogo: "/static/pet-test.png",
					brandProductCount: 568,
					brandFollowerCount: 2354,
					isFavorite: false,
					description: "<p>本产品采用优质鸡肉为主要原料，搭配多种精选营养成分，专为小型犬设计...</p>",
					params: [{
							name: "品牌",
							value: "品牌名称"
						},
						{
							name: "产地",
							value: "中国"
						},
						{
							name: "净含量",
							value: "2.5kg"
						},
						{
							name: "保质期",
							value: "12个月"
						},
						{
							name: "适用种类",
							value: "小型犬"
						},
						{
							name: "适用年龄",
							value: "成犬"
						}
					],
					reviews: [{
							username: "用户**123",
							avatar: "/static/pet-test.png",
							rating: 5,
							content: "狗狗很喜欢吃，吃了这个狗粮精神状态好很多，毛发也亮了。包装严实，价格也合适，已经回购多次了！",
							images: ["/static/pet-test.png", "/static/pet-test.png"],
							time: "2025-03-15",
							spec: "规格：2.5kg"
						},
						{
							username: "宠物达人",
							avatar: "/static/pet-test.png",
							rating: 4,
							content: "质量不错，就是送货有点慢，家里的两只小泰迪都很爱吃。",
							images: [],
							time: "2025-03-10",
							spec: "规格：2.5kg"
						}
					]
				},
				productImages: '',
				productSpecs: [{
						name: "规格",
						options: [{
								label: "1.5kg",
								value: "1.5kg",
								available: true
							},
							{
								label: "2.5kg",
								value: "2.5kg",
								available: true
							},
							{
								label: "5kg",
								value: "5kg",
								available: false
							}
						]
					},
					{
						name: "口味",
						options: [{
								label: "鸡肉味",
								value: "chicken",
								available: true
							},
							{
								label: "牛肉味",
								value: "beef",
								available: true
							},
							{
								label: "鱼肉味",
								value: "fish",
								available: true
							}
						]
					}
				],
				selectedSpecs: {
					"规格": "2.5kg",
					"口味": "chicken"
				},
				quantity: 1,
				tabs: ["商品介绍", "规格参数"],
				currentTab: 0,
				recommendedProducts: [],
				cartItemCount: 5,
				showCartPopup: false
			}
		},
		mounted() {
			this.productId = getApp().globalData.currentGoodId;
			console.log(this.productId);
			this.fetchProductInfo();
			this.fetchCartData()
			this.getGoods();
		},
		methods: {
			async getGoods() {
				try {
					const result = await productApi.getProductList()
					this.recommendedProducts = result.slice(0, 8)
				} catch (error) {
					uni.showToast({
						title: '获取商品失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取商品失败', error);
				}
			},
			// 获取商品信息
			async fetchProductInfo() {
				try {
					const result = await productApi.getProductDetail({
						id: this.productId
					})
					this.productInfo.name = result.tradeName
					this.productInfo.tags = result.label
					this.productInfo.price = result.prices
					this.productInfo.salesCount = result.salesVolume
					this.productInfo.description = result.introduction
					this.productImages = result.picture;
					console.log(this.productImages);
					// 处理标签 - 将字符串拆分为数组
					this.productInfo.tags = result.label ? result.label.split(' ') : [];

					// 处理评分 - 转换为数字
					this.productInfo.rating = parseFloat(result.evaluate.replace('分', ''));

					// 更新商品参数
					this.productInfo.params = [{
							name: "品牌",
							value: result.brand
						},
						{
							name: "产地",
							value: result.origin
						},
						{
							name: "净含量",
							value: result.netContent
						},
						{
							name: "适用种类",
							value: result.applicableType
						},
						{
							name: "适用年龄",
							value: result.applicableAge
						},
						{
							name: "口味",
							value: result.taste
						}
					];

					// 更新商品规格选项
					this.productSpecs = [{
							name: "规格",
							options: [{
								label: result.standards,
								value: result.standards,
								available: true
							}]
						},
						{
							name: "口味",
							options: [{
								label: result.taste,
								value: result.taste,
								available: true
							}]
						}
					];

					// 设置默认选中的规格
					this.selectedSpecs = {
						"规格": result.standards,
						"口味": result.taste
					};
					console.log(result);

				} catch (error) {
					uni.showToast({
						title: '获取商品信息失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('获取商品信息失败', error);
				}
			},

			// 获取当前选择的规格文本
			getSelectedSpecsText() {
				let result = '';
				for (const key in this.selectedSpecs) {
					if (result) result += ', ';

					// 获取选中规格的显示文本
					const spec = this.productSpecs.find(s => s.name === key);
					if (spec) {
						const option = spec.options.find(o => o.value === this.selectedSpecs[key]);
						if (option) {
							result += `${key}: ${option.label}`;
						}
					}
				}
				if (result) result += `, 数量: ${this.quantity}`;
				return result || '请选择商品规格';
			},

			// 选择规格
			selectSpec(specName, value, available) {
				if (!available) return;
				this.selectedSpecs[specName] = value;
			},

			// 增加数量
			increaseQuantity() {
				this.quantity++;
			},

			// 减少数量
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},

			// 切换标签
			switchTab(index) {
				this.currentTab = index;
			},

			// 加载更多评价
			loadMoreReviews() {
				uni.showToast({
					title: '加载更多评价',
					icon: 'none'
				});
			},

			// 切换收藏状态
			toggleFavorite() {
				this.productInfo.isFavorite = !this.productInfo.isFavorite;
				uni.showToast({
					title: this.productInfo.isFavorite ? '已加入收藏' : '已取消收藏',
					icon: 'none'
				});
			},

			// 联系客服
			contactShop() {
				uni.showToast({
					title: '客服功能即将上线',
					icon: 'none'
				});
			},

			async fetchCartData() {
				try {
					const result = await productApi.getShopCar()
					this.cartItemCount = result.length;

				} catch (error) {
					console.error('获取购物车信息失败：', error);
				}

			},

			// 加入购物车
			async addToCart() {
				// 校验规格是否选择完整
				for (const spec of this.productSpecs) {
					if (!this.selectedSpecs[spec.name]) {
						uni.showToast({
							title: `请选择${spec.name}`,
							icon: 'none'
						});
						return;
					}
				}

				try {
					const result = await productApi.putShopCar({
						goodsId: this.productId,
						goodsNum: this.quantity
					})

					// 模拟添加购物车
					this.cartItemCount++;

					// 显示加入购物车成功提示
					this.showCartPopup = true;
					setTimeout(() => {
						this.showCartPopup = false;
					}, 1500);
				} catch (error) {
					uni.showToast({
						title: '加入购物车失败: ' + (error.message || '未知错误'),
						icon: 'none'
					});
					console.error('加入购物车失败：', error);
				}
			},

			// 立即购买
			buyNow() {
				// 校验规格是否选择完整
				for (const spec of this.productSpecs) {
					if (!this.selectedSpecs[spec.name]) {
						uni.showToast({
							title: `请选择${spec.name}`,
							icon: 'none'
						});
						return;
					}
				}

				// 跳转到订单确认页面
				uni.navigateTo({
					url: '/pages/order/confirm'
				});
			},

			// 导航到购物车页面
			navigateToCart() {
				uni.navigateTo({
					url: '/pages/shop/shopCar'
				});
			},

			// 导航到品牌详情页
			navigateToBrand(brandId) {
				uni.navigateTo({
					url: `/pages/brand/detail?id=${brandId}`
				});
			},

			// 导航到商品详情
			navigateToDetail(id) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${id}`
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 0 20rpx;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
		/* 为底部栏留出空间 */
	}

	/* 轮播图样式 */
	.product-swiper {
		height: 750rpx;
		border-radius: 20rpx;
		overflow: hidden;

	}

	.product-gallery-section {
		flex: 0 0 45%;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}

	/* 商品基本信息样式 */
	.product-basic-info {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		margin-top: 20rpx;
	}

	.product-price-row {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.product-price {
		font-size: 40rpx;
		font-weight: bold;
		color: #FF6B35;
	}

	.product-original-price {
		font-size: 28rpx;
		color: #999;
		text-decoration: line-through;
		margin-left: 15rpx;
	}

	.product-tags {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 15rpx;
	}

	.product-tag {
		font-size: 22rpx;
		color: #FF6B35;
		background-color: rgba(255, 107, 107, 0.1);
		padding: 4rpx 10rpx;
		margin-right: 10rpx;
		margin-bottom: 10rpx;
		border-radius: 6rpx;
	}

	.product-name {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
		line-height: 1.4;
	}

	.product-stats {
		display: flex;
		font-size: 26rpx;
		color: #666;
	}

	.product-stat {
		margin-right: 30rpx;
	}

	/* 商品规格选择样式 */
	.product-specs {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		margin-top: 20rpx;
	}

	.specs-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.specs-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.specs-selected {
		font-size: 24rpx;
		color: #666;
	}

	.specs-section {
		margin-bottom: 20rpx;
	}

	.spec-type {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 15rpx;
	}

	.spec-options {
		display: flex;
		flex-wrap: wrap;
	}

	.spec-option {
		background-color: #f5f5f5;
		border-radius: 8rpx;
		padding: 10rpx 20rpx;
		margin-right: 15rpx;
		margin-bottom: 15rpx;
		font-size: 26rpx;
		color: #333;
	}

	.spec-option.active {
		background-color: rgba(255, 107, 107, 0.1);
		color: #FF6B35;
		border: 1rpx solid #FF6B35;
	}

	.spec-option.disabled {
		color: #ccc;
		background-color: #f5f5f5;
		cursor: not-allowed;
	}

	.quantity-section {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
	}

	.quantity-label {
		font-size: 28rpx;
		color: #333;
		margin-right: 20rpx;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		border: 1rpx solid #e0e0e0;
		border-radius: 6rpx;
	}

	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 30rpx;
		background-color: #f5f5f5;
	}

	.quantity-input {
		width: 80rpx;
		height: 60rpx;
		text-align: center;
		font-size: 28rpx;
		border-left: 1rpx solid #e0e0e0;
		border-right: 1rpx solid #e0e0e0;
	}

	/* 店铺信息样式 */
	.shop-info {
		display: flex;
		align-items: center;
		background-color: #fff;
		padding: 20rpx;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}

	.shop-logo {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.shop-detail {
		flex: 1;
		margin-left: 15rpx;
	}

	.shop-name {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 8rpx;
	}

	.shop-stats {
		display: flex;
		font-size: 22rpx;
		color: #666;
	}

	.shop-stat {
		margin-right: 20rpx;
	}

	.btn-check-shop {
		padding: 8rpx 20rpx;
		font-size: 24rpx;
		border-radius: 30rpx;
		background-color: #fff;
		color: #FF6B35;
		border: 1rpx solid #FF6B35;
	}

	/* 商品详情区域样式 */
	.product-details {
		background-color: #fff;
		border-radius: 20rpx;
		margin-top: 20rpx;
		overflow: hidden;
	}

	.tabs {
		display: flex;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #333;
		position: relative;
	}

	.tab.active {
		color: #FF6B35;
		font-weight: bold;
	}

	.tab.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 25%;
		width: 50%;
		height: 4rpx;
		background-color: #FF6B35;
	}

	.tab-content {
		padding: 20rpx;
	}

	/* 商品介绍 */
	.product-description {
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
	}

	.detail-images {
		margin-top: 20rpx;
	}

	.detail-image {
		width: 100%;
		margin-bottom: 10rpx;
	}

	/* 规格参数 */
	.product-params {}

	.param-item {
		display: flex;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.param-name {
		width: 180rpx;
		font-size: 26rpx;
		color: #666;
	}

	.param-value {
		flex: 1;
		font-size: 26rpx;
		color: #333;
	}

	/* 用户评价 */
	.review-stats {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.review-rating {
		font-size: 50rpx;
		font-weight: bold;
		color: #FF6B35;
		margin-right: 20rpx;
	}

	.review-stars {
		margin-right: 20rpx;
	}

	.star {
		color: #ccc;
		font-size: 32rpx;
	}

	.star.filled {
		color: #FF6B35;
	}

	.review-stars.small .star {
		font-size: 24rpx;
	}

	.review-count {
		font-size: 26rpx;
		color: #666;
	}

	.review-list {
		margin-top: 20rpx;
	}

	.review-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.review-header {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.reviewer-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		margin-right: 10rpx;
	}

	.reviewer-name {
		font-size: 26rpx;
		color: #333;
		margin-right: 15rpx;
	}

	.review-content {
		font-size: 26rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 15rpx;
	}

	.review-images {
		display: flex;
		margin-bottom: 15rpx;
	}

	.review-image {
		width: 150rpx;
		height: 150rpx;
		margin-right: 10rpx;
		border-radius: 8rpx;
	}

	.review-footer {
		display: flex;
		font-size: 24rpx;
		color: #999;
	}

	.review-time {
		margin-right: 20rpx;
	}

	.load-more {
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
	}

	/* 猜你喜欢 */
	.recommended {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.recommended-list {
		white-space: nowrap;
	}

	.recommended-item {
		display: inline-block;
		width: 200rpx;
		margin-right: 20rpx;
	}

	.recommended-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 8rpx;
	}

	/* 以下是需要补充的样式 */

	.recommended-name {
		font-size: 24rpx;
		color: #333;
		white-space: normal;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		height: 70rpx;
		margin: 10rpx 0;
	}

	.recommended-price {
		font-size: 24rpx;
		color: #FF6B35;
		font-weight: bold;
	}

	/* 底部购买栏样式 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		align-items: center;
		padding: 10rpx 20rpx;
		background-color: #fff;
		border-top: 1rpx solid #f0f0f0;
		z-index: 100;
	}

	.action-buttons {
		display: flex;
		flex: 1;
	}

	.action-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 0 20rpx;
		position: relative;
	}

	.action-icon {
		font-size: 40rpx;
	}

	.action-text {
		font-size: 20rpx;
		color: #666;
		margin-top: 5rpx;
	}

	.cart-badge {
		position: absolute;
		top: -5rpx;
		right: 10rpx;
		background-color: #FF6B35;
		color: #fff;
		font-size: 18rpx;
		border-radius: 20rpx;
		min-width: 30rpx;
		height: 30rpx;
		text-align: center;
		line-height: 30rpx;
		padding: 0 5rpx;
	}

	.purchase-buttons {
		display: flex;
	}

	.btn-add-cart,
	.btn-buy-now {
		width: 180rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		font-size: 26rpx;
		border-radius: 35rpx;
		margin-left: 10rpx;
	}

	.btn-add-cart {
		background-color: #FFF0F0;
		color: #FF6B35;
		border: 1rpx solid #FF6B35;
	}

	.btn-buy-now {
		background-color: #FF6B35;
		color: #fff;
	}

	/* 购物车成功提示 */
	.add-cart-popup {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(0, 0, 0, 0.7);
		border-radius: 20rpx;
		padding: 20rpx 30rpx;
		z-index: 1000;
	}

	.popup-content {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.popup-icon {
		font-size: 36rpx;
		color: #fff;
		margin-right: 10rpx;
	}

	.popup-text {
		font-size: 28rpx;
		color: #fff;
	}
</style>